package com.spic.business.train.trainInfo.service.impl;


import com.spic.business.common.datascope.anotation.BusinessDataScope;
import com.spic.business.train.autonomic.domain.TrainAutonomicLearning;
import com.spic.business.train.autonomic.service.ITrainAutonomicLearningService;
import com.spic.business.train.createtest.domain.TrainExam;
import com.spic.business.train.createtest.service.ITrainExamService;
import com.spic.business.train.plan.service.ITrainPlanService;
import com.spic.business.train.plan.service.ITrainPlanStatusService;
import com.spic.business.train.trainInfo.domain.TrainInfo;
import com.spic.business.train.trainInfo.dto.*;
import com.spic.business.train.trainInfo.mapper.TrainInfoMapper;
import com.spic.business.train.trainInfo.service.ITrainInfoService;
import com.spic.business.train.trainInfoCourseware.domain.TrainInfoCourseware;
import com.spic.business.train.trainInfoCourseware.mapper.TrainInfoCoursewareMapper;
import com.spic.business.train.trainUser.domain.TrainUser;
import com.spic.business.train.trainUser.mapper.TrainUserMapper;
import com.spic.common.core.exception.ServiceException;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.core.utils.UUIDUtil;
import com.spic.common.security.utils.cache.DeptCacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 培训信息Service业务层处理
 *
 * @author spic
 * @date 2021-10-15
 */
@Service
public class TrainInfoServiceImpl implements ITrainInfoService
{

    /*@Autowired
    private RemoteUserService userService;*/
    @Autowired
    private TrainInfoMapper trainInfoMapper;

    @Autowired
    private TrainUserMapper trainUserMapper;
    @Autowired
    private TrainInfoCoursewareMapper trainInfoCoursewareMapper;
    @Autowired
    private ITrainAutonomicLearningService trainAutonomicLearningService;
    @Autowired
    private ITrainPlanService planService;
    @Autowired
    private ITrainPlanStatusService trainPlanStatusService;
    @Autowired
    private ITrainExamService trainExamService;

   /* @Autowired
    private RemoteDictDataService dictDataService;*/
    /**
     * 查询培训信息
     *
     * @param id 培训信息主键
     * @return 培训信息
     */
    @Override
    public TrainInfo selectTrainInfoById(String id)
    {
        TrainInfo trainInfo= trainInfoMapper.selectTrainInfoById(id);

        return trainInfo;
    }
/*
    *//**
     * 查询培训信息导出信息
     *
     * @param trainInfo 培训信息
     * @return 培训信息
     *//*
    @Override

    public List<TrainInfo> selectTrainInfoListToexport(TrainInfo trainInfo)
    {
        Map<Long,String> map= userService.map().getData();
        int i=1;//序号
        List<TrainInfo> trainInfos=trainInfoMapper.selectTrainInfoList(trainInfo);
        for (TrainInfo trainInfo1:
                trainInfos) {
            trainInfo1.setRownum(i);
            trainInfo1.setDeptName(map.get(trainInfo1.getDept()));
//            System.out.println(map.toString());
//            System.out.println(trainInfo1.getDept());
//            System.out.println(map.get(trainInfo1.getDept()));
            trainInfo1.setTotalPersonnel(trainInfo1.calculationTotalPersonnel());
            i++;
        }


        return trainInfos;
    }*/
    /**
     * 查询培训信息列表
     *
     * @param trainListDto 培训信息
     * @return 培训信息
     */
    @Override
    @BusinessDataScope(alias = "p.")
    public List<TrainInfo> selectTrainInfoList(TrainListDto trainListDto)
    {
        trainListDto.setDept(Long.valueOf(SecurityUtils.getDeptId()));
        List<TrainInfo> trainInfos=trainInfoMapper.selectTrainInfoList(trainListDto);
        trainInfos.forEach(trainInfo -> {
            try {
                trainInfo.getTrainPlan().setDeptName(DeptCacheUtils.getValue(trainInfo.getTrainPlan().getDeptId()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        return trainInfos;
    }


    /**
     * 新增培训信息
     *
     * @param trainInfoDto 培训信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTrainInfo(TrainInfoDto trainInfoDto)
    {
        //培训信息集合
        List<TrainInfo> trainInfos=new ArrayList<>();

        //用户课件集合
        List<TrainInfoCourseware> trainInfoCoursewares = new ArrayList<>();
        //用户自主学习集合
        List<TrainAutonomicLearning> trainAutonomicLearnings = new ArrayList<>();

        for (ClassDto classDto:trainInfoDto.getclassDtos()) {
            //新增培训用户集合
            List<TrainUser> trainUsers=new ArrayList<>();
            TrainInfo trainInfo=new TrainInfo();
            trainInfo.setId(UUIDUtil.createUUID());
            trainInfo.setPlanId(trainInfoDto.getPlanId());
            trainInfo.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
            trainInfo.setTrainPlanShiftId(classDto.getTrainPlanShiftId());
            trainInfos.add(trainInfo);
            for (Long userId:classDto.getUserIds()) {
                TrainUser trainUser=new TrainUser();
                trainUser.setTrainInfoId(trainInfo.getId());
                trainUser.setUserId(userId);
                trainUsers.add(trainUser);
            }
            trainUserMapper.insertTrainUsers(trainUsers);

            if(trainInfoDto.getTrainCoursewareList()!=null&&trainInfoDto.getTrainCoursewareList().size()!=0) {
                for (TrainCourseWareDTO trainCourseWareDTO : trainInfoDto.getTrainCoursewareList()) {
                    TrainInfoCourseware trainInfoCourseware = new TrainInfoCourseware();
                    trainInfoCourseware.setId(UUIDUtil.createUUID());
                    trainInfoCourseware.setTrainInfoId(trainInfo.getId());
                    trainInfoCourseware.setTrainCoursewareId(trainCourseWareDTO.getTrainCoursewareId());
                    trainInfoCoursewares.add(trainInfoCourseware);
                    for (TrainUser trainuser : trainUsers) {
                        TrainAutonomicLearning trainAutonomicLearning = new TrainAutonomicLearning();
                        trainAutonomicLearning.setTrainUserId(trainuser.getId());
                        trainAutonomicLearning.setCoursewareId(trainCourseWareDTO.getTrainCoursewareId());
                        trainAutonomicLearning.setTrainTime(trainCourseWareDTO.getTrainTime());
                        trainAutonomicLearnings.add(trainAutonomicLearning);

                    }
                }
                trainInfoCoursewareMapper.insertTrainInfoCoursewares(trainInfoCoursewares);//新增培训课件表
                trainAutonomicLearningService.batchInsert(trainAutonomicLearnings);//新增用户课件表(课件自主学习)
            }

        }



       /* // trainInfo.setCreateTime(DateUtils.getNowDate());
        //如果有关联计划 将计划的执行状态 改为执行中
        if(StringUtils.isNotEmpty(trainInfo.getPlanId())){
            TrainPlan trainPlan=new TrainPlan();
            trainPlan.setId(trainInfo.getPlanId());
            trainPlan.setImplementFlag("1");
            trainPlanMapper.updateTrainPlan(trainPlan);
        }


        }*/
        return trainInfoMapper.insertTrainInfos(trainInfos);
    }


    /**
     * 修改培训信息
     *
     * @param trainInfoDto 培训信息
     * @return 结果
     */
    @Override
    public int updateTrainInfo(TrainInfoDto trainInfoDto) throws ServiceException {

        if("0".equals(planService.selectTrainPlanById(trainInfoDto.getPlanId()).getImplementFlag())){

            List<String> trainInfoIds=trainInfoMapper.selectTrainInfoByPlanId(trainInfoDto.getPlanId());
            for (String trainInfoId:
                    trainInfoIds) {
                trainAutonomicLearningService.deleteTrainAutonomicLearningByTrainUserIds(trainUserMapper.selectIds(trainInfoId));//删除用户课件表
                trainUserMapper.deleteTrainUserByTrainId(trainInfoId);//删除培训用户
                trainInfoCoursewareMapper.deleteTrainInfoCoursewareByTrainInfoId(trainInfoId);//删除培训课件表

            }


            trainInfoMapper.deleteTrainInfoByPlanId(trainInfoDto.getPlanId());
            return insertTrainInfo(trainInfoDto);
        }else{
            throw  new ServiceException("此方案已执行,不允许修改");
        }


    }

    /**
     * 批量删除培训信息
     *
     * @param ids 需要删除的培训方案主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTrainInfoByIds(String[] ids)throws ServiceException
    {
        int num=0;
        for (String planId:ids){

            if("0".equals(planService.selectTrainPlanById(planId).getImplementFlag())){


                List<String> trainInfoIds=trainInfoMapper.selectTrainInfoByPlanId(planId);
                for (String trainInfoId:
                        trainInfoIds) {
                    trainAutonomicLearningService.deleteTrainAutonomicLearningByTrainUserIds(trainUserMapper.selectIds(trainInfoId));//删除用户课件表
                    trainUserMapper.deleteTrainUserByTrainId(trainInfoId);//删除培训用户
                    trainInfoCoursewareMapper.deleteTrainInfoCoursewareByTrainInfoId(trainInfoId);//删除培训课件表

                }


               num += trainInfoMapper.deleteTrainInfoByPlanId(planId);
            }else{
                throw  new ServiceException("此方案已执行,不允许删除");
            }
        }

        return num;

    }

    /**
     * 删除培训信息信息
     *
     * @param id 培训信息主键
     * @return 结果
     */
    @Override
    public int deleteTrainInfoById(String id)
    {
        return trainInfoMapper.deleteTrainInfoById(id);
    }

    /**
     * 开启培训
     */
    public int starTrainInfoByIds(String[] ids){

        //修改方案状态
        for (String id:ids){
            TrainInfo trainInfo= trainInfoMapper.selectTrainInfoById(id);
            if(trainInfo !=null){
                trainPlanStatusService.updatePlanStatus(trainInfo.getPlanId(), ITrainPlanStatusService.Status.DOING);
            }
        }

        return trainInfoMapper.starTrainInfoByIds(ids);
    }
    /**
     * 开启培训
     */
    @Override
    public int updateTrainInfo(TrainInfo trainInfo) {
        //修改方案状态
        trainPlanStatusService.updatePlanStatus(trainInfo.getPlanId(), ITrainPlanStatusService.Status.DOING);
        return trainInfoMapper.updateTrainInfo(trainInfo);
    }

    /**
     * 查询符合条件还没创建考试的培训
     */

    public List<TrainInfoVo>  selectTrainInfoListNotInexam(){
        return trainInfoMapper.selectTrainInfoListNotInexam();
    }
    /**
     * 用户培训结束后判断培训是否结束
     *  @param id 培训信息主键
     */
    @Transactional
    public void  updateTrainInfoforUserTrainEnd(String id){
        TrainInfo trainInfo=trainInfoMapper.selectTrainInfoById(id);
        //本次培训所用用户都完成培训,修改培训状态
        if(trainUserMapper.countTrainNotEnd(id)==0){
            trainInfo.setImplementState(3);
            trainInfoMapper.updateTrainInfo(trainInfo);

            //本方案所有培训均完成,修改方案状态
            if(trainInfoMapper.countTrainEnd(trainInfo.getPlanId())!=0){
                trainPlanStatusService.updatePlanStatus(trainInfo.getPlanId(), ITrainPlanStatusService.Status.DONE);
            }


        }
    }

    /**
     * 判断考试是否已经结束
     * 若已结束,即时有人未参加考试也把train_info表的implementState改为3,培训结束的状态
     */
    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void updateImplementState() {
        Date currentTime = new Date();
        TrainListDto trainListDto = new TrainListDto();
        trainListDto.setImplementState(1);
        List<TrainInfo> trainInfos = trainInfoMapper.selectTrainInfoList(trainListDto);
        for (int i = 0; i < trainInfos.size(); i++) {
            String planId = trainInfos.get(i).getPlanId();
            TrainExam trainExam = new TrainExam();
            trainExam.setTrainId(planId);
            trainExam.setState(0L);
            List<TrainExam> trainExams = trainExamService.selectTrainExamListNoDataScope(trainExam);
            if(trainExams.size() > 0) {
                Date endTime = trainExams.get(0).getEndTime();
                if(currentTime.compareTo(endTime) > 0) {
                    TrainInfo trainInfo= new TrainInfo();
                    trainInfo.setImplementState(3);
                    trainInfo.setId(trainInfos.get(i).getId());
                    trainInfoMapper.updateTrainInfo(trainInfo);
                }
            }
        }
    }
    /**
     * 查询我的培训信息列表
     *
     * @param trainListDto 培训信息
     * @return 培训信息集合
     */
    @Override
    public List<TrainInfo> listByUserId(TrainListDto trainListDto) {
        trainListDto.setUserId(SecurityUtils.getUserId());
        List<TrainInfo> trainInfos=trainInfoMapper.selectTrainInfoListByUserId(trainListDto);

        return trainInfos;
    }

    @Override
    public List<TrainInfoAPPVo> listByUserIdForApp(TrainInfoAPPDto trainInfoAPPDto) {
        trainInfoAPPDto.setUserId(SecurityUtils.getUserId());

        return trainInfoMapper.selectTrainInfoListByUserIdForApp(trainInfoAPPDto);
    }

    @Override
    public List<TrainInfoAPPVo> getListByTrainInfoForApp(TrainInfoAPPDto trainInfoAPPDto) {
        trainInfoAPPDto.setUserId(SecurityUtils.getUserId());

        return trainInfoMapper.selectListByTrainInfoForApp(trainInfoAPPDto);
    }

    @Override
    public List<TrainInfoAPPVo> getListByTrainInfoForAppCount(TrainInfoAPPDto trainInfoAPPDto)
    {
        return trainInfoMapper.selectListByTrainInfoForAppCount(trainInfoAPPDto);
    }
}
